package com.spring.mongo.config;

import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.net.UnknownHostException;

/**
 * ClassName: SpringMongoConfig
 * Description:
 * Date: 2017/9/13 9:58
 *
 * @author SAM SHO
 * @version V1.0
 */
@Configuration
@ComponentScan(basePackages = "com.spring.mongo")
public class SpringMongoConfig {

    /**
     * <mongo:mongo host="localhost" port="27017">
     * <mongo:options connections-per-host="8"
     * threads-allowed-to-block-for-connection-multiplier="4"
     * connect-timeout="1000"
     * max-wait-time="1500}"
     * auto-connect-retry="true"
     * socket-keep-alive="true"
     * socket-timeout="1500"
     * slave-ok="true"
     * write-number="1"
     * write-timeout="0"
     * write-fsync="true"/>
     * </mongo:mongo/>
     * <p>带副本
     * <mongo:mongo id="replicaSetMongo" replica-set="127.0.0.1:27017,localhost:27018"/>
     *
     * @return
     * @throws UnknownHostException
     */
    @Bean
    public MongoClient mongo() throws UnknownHostException {
        return new MongoClient("192.168.117.200");
    }

    /**
     * 或者定义 MongoClientFactoryBean 是一样的，和 MongoClient 一样
     *
     * @return
     */
    @Bean
    public MongoClientFactoryBean mongoBean() {
        MongoClientFactoryBean mongo = new MongoClientFactoryBean();
        mongo.setHost("192.168.117.200");
        return mongo;
    }

    @Bean
    public MongoDbFactory mongoDbFactory() throws Exception {
//        UserCredentials userCredentials = new UserCredentials("joe", "secret");
        return new SimpleMongoDbFactory(new MongoClient("192.168.117.200"), "test");
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
//        UserCredentials userCredentials = new UserCredentials("joe", "secret");
//        return new MongoTemplate(mongo(), "test", userCredentials);

        return new MongoTemplate(mongoDbFactory());
    }
}
